package cn.com.yangzhenyu.brick.controller;

import cn.com.yangzhenyu.brick.example.CommonExample;
import cn.com.yangzhenyu.brick.exception.MySQLException;
import cn.com.yangzhenyu.brick.pojo.*;
import cn.com.yangzhenyu.brick.service.HttpService;
import cn.com.yangzhenyu.brick.service.TableService;
import cn.com.yangzhenyu.brick.util.JacksonUtils;
import cn.com.yangzhenyu.brick.util.TokenUtils;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 微信小程序
 * 微信 各种与微信API的接口
 * Created with IntelliJ IDEA
 * Created By 杨振宇
 * Date: 2018/8/19
 * Time: 15:53
 */
@Controller
@RequestMapping("/wx")
public class WeiXinController {

    @Value("${wx.appid}")
    private String appID = null;
    @Value("${wx.appsecret}")
    private String appSecret = null;
    @Value("${wx.grant_type}")
    private String grantType = null;

    @Resource
    private HttpService httpService;

    @Resource
    private TableService tableService;


    @RequestMapping(value = "appLogin")
    @ResponseBody
    public ApiResult appLogin(String username,String password) {
        if (StrUtil.hasBlank(username,password)) {
            return ApiResult.error(-1, "参数不能为空");
        }
        try {
            CommonExample userExample = new CommonExample("user");
            CommonExample.Criteria userCriteria = userExample.createCriteria();
            userCriteria.andColumnEqualTo("username", username);
            LinkedHashMap<String, Object> userInfo = tableService.findOneData(userExample);
            if(null != userInfo && TokenUtils.appPasswordAuto(MapUtil.getStr(userInfo,"password"),password)){
                userInfo.put("password","");
                userInfo.put("token", TokenUtils.token(MapUtil.getInt(userInfo,"user_id")));
                return ApiResult.success("APP登录成功").data(userInfo);
            }
        } catch (MySQLException e) {
            e.printStackTrace();
        }
        return ApiResult.error("登录失败");
    }

    @RequestMapping(value = "login")
    @ResponseBody
    public ApiResult get(String code) {
        if (StrUtil.hasBlank(code)) {
            return ApiResult.error(-1, "code不能为空");
        }
        HttpRequestData httpRequestData = new HttpRequestData();
        httpRequestData.setUrl("https://api.weixin.qq.com/sns/jscode2session");
        httpRequestData.setHeaders(MapUtil.of("Content-Type", "application/json"));
        httpRequestData.setMethod("GET");
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appID);
        params.put("secret", appSecret);
        params.put("js_code", code);
        params.put("grant_type", grantType);
        httpRequestData.setParams(params);
        HttpResult httpResult = httpService.go(httpRequestData);

        if (null != httpResult) {
            int status = httpResult.getStatus();
            if (200 == status || 302 == status) {
                try {

                    WxLoginInfo wxLoginInfo = JSONUtil.toBean(httpResult.getBody(), WxLoginInfo.class);
                    //加到数据库 有则改 无则加
                    CommonExample wxUserExample = new CommonExample("wx_user");
                    CommonExample.Criteria wxUserCriteria = wxUserExample.createCriteria();
                    wxUserCriteria.andColumnEqualTo("openid", wxLoginInfo.getOpenid());
                    Long size = tableService.findListCount(wxUserExample);
                    boolean isModelShow = false;
                    if (size > 0) {
                        BaseData data = BaseData.createBaseData("wx_user");
                        data.putWhere("openid", wxLoginInfo.getOpenid());
                        data.putData("session_key", wxLoginInfo.getSession_key());
                        data.putData("expires_in", wxLoginInfo.getExpires_in());
                        tableService.editData(data);
                    } else {
                        isModelShow = true;
                        BaseData data = BaseData.createBaseData("wx_user");
                        data.putData("openid", wxLoginInfo.getOpenid());
                        data.putData("session_key", wxLoginInfo.getSession_key());
                        data.putData("expires_in", wxLoginInfo.getExpires_in());
                        tableService.addData(data);
                        BaseData user = BaseData.createBaseData("user");
                        user.putData("openid", wxLoginInfo.getOpenid());
                        user.putData("username", "BRICK_"+wxLoginInfo.getOpenid());
                        user.putData("password", "123456");
                        user.putData("name", "BRICK用户"+wxLoginInfo.getOpenid());
                        int id = tableService.addData(user);
                        // 增加默认的标签 当初太蠢的设计
                        addTag(id);
                    }
                    return ApiResult.success("微信登录成功").data(resultMap(wxLoginInfo.getOpenid(),isModelShow));
                } catch (MySQLException e) {
                    return ApiResult.error(e.getErrorCode(), e.getErrorMessage());
                }
            } else {
                return ApiResult.error(status, httpResult.getMsg());
            }
        } else {
            return ApiResult.error(-999, "返回结果为空");
        }
    }

    @RequestMapping(value = "addInfo")
    @ResponseBody
    public ApiResult addInfo(String openid, String infoStr) {
        if (StrUtil.hasBlank(openid)) {
            return ApiResult.error(-1, "openid不能为空");
        }
        try {
            Map<String, Object> info = JacksonUtils.json2map(infoStr);
            if(info == null) return ApiResult.error(600, "传来数据为空..");
            BaseData data = BaseData.createBaseData("wx_user");
            data.putWhere("openid", openid);
            data.putData("avatarUrl", info.get("avatarUrl"));
            data.putData("city", info.get("city"));
            data.putData("country", info.get("country"));
            data.putData("gender", info.get("gender"));
            data.putData("language", info.get("language"));
            data.putData("nickName", info.get("nickName"));
            data.putData("province", info.get("province"));

            tableService.editData(data);
            BaseData user = BaseData.createBaseData("user");
            user.putWhere("openid", openid);
            user.putData("wx_info", infoStr);
            user.putData("name", info.get("nickName"));
            tableService.editData(user);

            return ApiResult.success("保存成功").data(resultMap(openid,false));
        } catch (MySQLException e) {
            return ApiResult.error(e.getErrorCode(), e.getErrorMessage());
        }
    }

    private Map<String,Object> resultMap(String openid,boolean isModelShow) throws MySQLException {
        //查找本地的user信息传回去 去掉密码
        CommonExample userExample = new CommonExample("user");
        CommonExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andColumnEqualTo("openid", openid);
        LinkedHashMap<String, Object> userInfo = tableService.findOneData(userExample);
        userInfo.put("password", null);
        CommonExample example = new CommonExample("wx_user");
        CommonExample.Criteria criteria = example.createCriteria();
        criteria.andColumnEqualTo("openid", openid);
        LinkedHashMap<String, Object> wxInfo = tableService.findOneData(example);
        if(wxInfo.get("avatarUrl") == null){
            isModelShow = true;
        }
        wxInfo.put("session_key", null);
        wxInfo.put("expires_in", null);
        Map<String,Object> result = MapUtil.newHashMap();
        result.put("userInfo",userInfo);
        result.put("token",TokenUtils.token(MapUtil.getInt(userInfo,"user_id")));
        result.put("isModelShow",isModelShow);
        result.put("wxInfo",wxInfo);
        return result;
    }

    private void addTag(int userId) throws MySQLException {
        // 记得来改图标
        String sql = "insert into tag(title,type,user,color,icon) values" +
                "    ('红包','0','" + userId + "','#FF969C','icon-shutiao')," +
                "    ('外快兼职','0','" + userId + "','#63B2C6','icon-pisa')," +
                "    ('投资收入','0','" + userId + "','#D66908','icon-mianbao')," +
                "    ('零花钱','0','" + userId + "','#8C9273','icon-tiantianquan')," +
                "    ('工资','0','" + userId + "','#6B86BD','icon-mianbao2')," +
                "    ('生活费','0','" + userId + "','#DEBE63','icon-mianbao1')," +
                "    ('药品','1','" + userId + "','#A5D7AD','icon-ziyuan')," +
                "    ('红包','1','" + userId + "','#FF969C','icon-ziyuan1')," +
                "    ('房租','1','" + userId + "','#94BEE7','icon-ziyuan4')," +
                "    ('淘宝','1','" + userId + "','#FFCB73','icon-ziyuan2')," +
                "    ('话费','1','" + userId + "','#8CC7F7','icon-ziyuan6')," +
                "    ('电影','1','" + userId + "','#A5E3E7','icon-ziyuan3')," +
                "    ('护肤彩妆','1','" + userId + "','#F7AAD6','icon-ziyuan5')," +
                "    ('生活用品','1','" + userId + "','#C6BEEF','icon-ziyuan7')," +
                "    ('酒水饮料','1','" + userId + "','#9CCBFF','icon-ziyuan14')," +
                "    ('零食','1','" + userId + "','#FFBA8C','icon-ziyuan12')," +
                "    ('买菜','1','" + userId + "','#9CDFD6','icon-ziyuan10')," +
                "    ('鞋包衣服','1','" + userId + "','#CEAEFF','icon-ziyuan9')," +
                "    ('水果','1','" + userId + "','#F7DB6B','icon-ziyuan13')," +
                "    ('交通','1','" + userId + "','#ADBAFF','icon-ziyuan15')," +
                "    ('其他','0','" + userId + "','#9CDFFF','icon-yinliao4')," +
                "    ('报销','0','" + userId + "','#B5DBD6','icon-yinliao7')," +
                "    ('餐饮','1','" + userId + "','#FFCB84','icon-ziyuan19')," +
                "    ('奖金','0','" + userId + "','#F7964A','icon-yinl')," +
                "    ('退款','0','" + userId + "','#BD757B','icon-bingjiling')," +
                "    ('现金','0','" + userId + "','#9CDFBD','icon-yinliao6');";
        tableService.executeSql(sql);
    }
}
